<template>
  <PageLayout full>
    <template #header>
      <HeaderLayout show-back :header-style="headerStyle">
        <view>
          {{
            brand === 'SIEMENS'
              ? $t('BIWD.CustomProgram.SIEMENS.Navigate.Title')
              : $t('BIWD.CustomProgram.BOSCH.Navigate.Title')
          }}</view
        >
      </HeaderLayout>
    </template>
    <view class="custom-program">
      <!-- 标题 -->
      <view class="custom-title">{{
        brand === 'SIEMENS' ? $t('BIWD.CustomProgram.SIEMENS.Label') : $t('BIWD.CustomProgram.BOSCH.Label')
      }}</view>

      <!-- 图片 -->
      <view class="custom-img">
        <image class="custom-image" :src="imgUrl"></image>
      </view>

      <!-- 温度和容量选择 -->
      <view class="custom-view">
        <!-- 温度  -->
        <view class="favoriteBox">
          <view class="favoriteViewTitle">{{ $t('BIWD.AddFavorite.Temperatures.Label') }}<text>(℃)</text></view>
          <view
            :style="tempIndex[0] === 0 ? 'opacity:0.3;pointer-events: none;' : 'opacity:1;'"
            @click="reduceCurIndex"
            class="pickerViewLeft"
          >
            <image src="@/pages/appliance/static/ic_decrease_icon.png"></image>
          </view>
          <picker-view
            mask-class="maskStyle"
            indicator-style="height: 45px;"
            indicator-class="clearBorder"
            class="pickerView"
            :value="tempIndex"
            @change="chooseTempCurIndex"
            @pickstart="startPick"
            @pickend="endPick"
          >
            <picker-view-column>
              <view
                class="pickerItem"
                v-for="(item, index) in tempList"
                :key="index"
                :class="{ active: index === tempIndex[0] }"
                style="line-height: 50px; text-align: center"
              >
                {{ item.value }}</view
              >
            </picker-view-column>
          </picker-view>
          <view
            :style="tempIndex[0] === tempList.length - 1 ? 'opacity: 0.3;pointer-events: none;' : 'opacity: 1;'"
            @click="addCurIndex"
            class="pickerViewRight"
          >
            <image src="@/pages/appliance/static/ic_add_icon.png"></image>
          </view>
        </view>
        <!-- 容量-->
        <view class="favoriteBox" v-if="millVisible">
          <view class="favoriteViewTitle">{{ $t('BIWD.AddFavorite.Mill.Label') }} <text>(ml)</text></view>
          <view
            :style="millIndex[0] === 0 ? 'opacity:0.3;pointer-events: none;' : 'opacity:1;'"
            @click="reduceMilliliter"
            class="pickerViewLeft"
          >
            <image src="@/pages/appliance/static/ic_decrease_icon.png"></image>
          </view>
          <picker-view
            mask-class="maskStyle"
            indicator-style="height: 45px;"
            indicator-class="clearBorder"
            class="pickerView"
            :value="millIndex"
            @change="chooseTempMilliliter"
            @pickstart="startPick"
            @pickend="endPick"
          >
            <picker-view-column>
              <view
                class="pickerItem"
                v-for="(item, index) in millList"
                :key="index"
                :class="{ active: index === millIndex[0] }"
                style="line-height: 50px; text-align: center"
              >
                {{ item.value }}</view
              >
            </picker-view-column>
          </picker-view>
          <view
            :style="millIndex[0] === millList.length - 1 ? 'opacity:0.3;pointer-events: none;' : 'opacity:1;'"
            @click="addMilliliter"
            class="pickerViewRight"
          >
            <image src="@/pages/appliance/static/ic_add_icon.png"></image>
          </view>
        </view>
      </view>
    </view>

    <template #footer>
      <FooterLayout fixed :size="footerSize" :footer-style="footerStyle">
        <view class="btn-box">
          <view class="btn save" @click="closeModal">{{ $t('BIWD.CustomProgram.Bottm.Cancel.Button') }}</view>
          <ActionButton style="flex-grow: 2" @click="save">{{
            $t('BIWD.CustomProgram.Bottm.Save.Button')
          }}</ActionButton>
        </view>
      </FooterLayout>
    </template>
  </PageLayout>
</template>

<script lang="ts">
export type PickerType = {
  value: number
}
</script>

<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import FooterLayout from '@/layout/page/footer.vue'
import ActionButton from '@/common/actionButton/actionButton.vue'

import { onLoad } from '@dcloudio/uni-app'
import type { BIWDController } from '@/controller/BIWD/definition'
import { actionDebounce, useEventReceiver } from '@/utils/mpHelper'
import { footerStyle, footerSize } from '@/layout/appliance/style'
import { BIWD_WATERTREATMENT_CUSTOM_TEMPERATURE, BIWD_WATERTREATMENT_CUSTOM_FILLQUANTITY } from '@/constants/WDCommand'
import type { BIWDSettingsType } from '@/api/biwd'
import { setHomeApplianceSettings } from '@/api/appliance'
import { useI18n } from 'vue-i18n'
import netconfig from '@/config/netconfig'

const headerStyle = {
  backgroundColor: '#fff',
}
const i18n = useI18n()
const imgUrl = computed(() => `${netconfig.ASSETSPRE_ICONS}BIWD_Custom_${brand.value === 'SIEMENS' ? 'SE' : 'BO'}.jpg`)

const settings = ref<BIWDSettingsType[]>([])
const control = ref<BIWDController.Control | null>(null)
useEventReceiver('control', (received: BIWDController.Control) => {
  control.value = received
  settings.value = control.value.store._datasource.settings as BIWDSettingsType[]
})

const TEMPLIST: PickerType[] = []
for (let i = 35; i <= 95; i = i + 5) {
  TEMPLIST.push({
    value: i,
  })
}
const MILLLIST: PickerType[] = []
for (let j = 100; j <= 500; j = j + 50) {
  TEMPLIST.push({
    value: j,
  })
}

const haId = ref('')
const brand = ref('')
const tempList = ref<PickerType[]>(TEMPLIST) //温度
const tempIndex = ref([2]) // 当前温度值下标
const opcityJianOne = ref(0) //温度减号默认模糊度
const opcityJiaOne = ref(0) //温度加号默认模糊度

const millVisible = ref(false)
const millList = ref<PickerType[]>(MILLLIST) //毫升
const millIndex = ref([4]) // 当前毫升下标
const opcityJianTwo = ref(0) //容量减号默认模糊度
const opcityJiaTwo = ref(0) //容量加号默认模糊度

onLoad((query: any) => {
  haId.value = query?.haId
  brand.value = query?.brand
})

watch(
  () => settings.value,
  (settings) => {
    if (!settings || settings.length === 0) return
    loadParams()
  }
)
watch(
  () => control.value?.store.customTemp,
  (value) => {
    if (tempList.value.length === 0) return
    let index = tempList.value.findIndex((item) => item.value === Number(value))
    tempIndex.value = [index]
  }
)
watch(
  () => control.value?.store.customMill,
  (value) => {
    if (millList.value.length === 0) return
    let index = millList.value.findIndex((item) => item.value === Number(value))
    millIndex.value = [index]
  }
)

/**
 * 获取调节参数数据
 */
async function loadParams() {
  if (settings.value && settings.value.length > 0) {
    let temperatures: PickerType[] = []
    let milliliter: PickerType[] = []
    let curTempIndex = 0
    let curMillIndex = 0
    let x = 0
    let y = 0
    settings.value.forEach((setting) => {
      if (setting.key === BIWD_WATERTREATMENT_CUSTOM_TEMPERATURE) {
        for (let i = Number(setting.min); i <= Number(setting.max); ) {
          temperatures.push({
            value: i,
          })
          if (Number(setting.value) === i) {
            curTempIndex = x
          }
          i = i + Number(setting.step)
          x++
        }
      } else if (setting.key === BIWD_WATERTREATMENT_CUSTOM_FILLQUANTITY) {
        millVisible.value = true
        for (let j = Number(setting.min); j <= Number(setting.max); ) {
          milliliter.push({
            value: j,
          })
          if (Number(setting.value) === j) {
            curMillIndex = y
          }
          j = j + Number(setting.step)
          y++
        }
      }
    })
    tempList.value = temperatures
    millList.value = milliliter
    setTimeout(() => {
      nextTick(() => {
        tempIndex.value = [curTempIndex]
        millIndex.value = [curMillIndex]
      })
    }, 200)
  }
}

/**
 * 选择温度
 * @param e
 */
function chooseTempCurIndex(e: WechatMiniprogram.PickerChange) {
  const indexes = e.detail.value as number[]
  changeJiaJian(indexes[0], 't')
  tempIndex.value = indexes
}

/**
 * 减少温度
 */
function reduceCurIndex() {
  let index = tempIndex.value[0] - 1
  index = index >= 0 ? index : 0
  changeJiaJian(index, 't')
  tempIndex.value = [index]
}

/**
 * 增加温度
 */
function addCurIndex() {
  let index = tempIndex.value[0] + 1
  index = index <= tempList.value.length - 1 ? index : tempList.value.length - 1
  changeJiaJian(index, 't')
  tempIndex.value = [index]
}

/**
 * 选择容量
 * @param e
 */
function chooseTempMilliliter(e: WechatMiniprogram.PickerChange) {
  const indexes = e.detail.value as number[]
  changeJiaJian(indexes[0], 'm')
  millIndex.value = indexes
}

/**
 * 减少容量
 */
function reduceMilliliter() {
  let index = millIndex.value[0] - 1
  index = index >= 0 ? index : 0
  changeJiaJian(index, 'm')
  millIndex.value = [index]
}

/**
 * 增加容量
 */
function addMilliliter() {
  let index = millIndex.value[0] + 1
  index = index <= millList.value.length - 1 ? index : millList.value.length - 1
  changeJiaJian(index, 'm')
  millIndex.value = [index]
}

/**
 * 监听滑动改变温度或容量时加减号透明度改变
 * @param index
 * @param type
 */
function changeJiaJian(index: number, type: string) {
  // t表示温度 m标识容量
  if (type == 't') {
    opcityJianOne.value = index
    opcityJiaOne.value = index
  } else {
    opcityJianTwo.value = index
    opcityJiaTwo.value = index
  }
}

const pickState = ref(false)
/**
 * 当滚动选择开始时候触发事件
 */
function startPick() {
  pickState.value = true
}

/**
 * 当滚动选择结束时候触发事件
 */
function endPick() {
  pickState.value = false
}

/**
 * 取消
 */
const closeModal = actionDebounce({
  showLoading: false,
  call: async () => {
    uni.navigateBack()
  },
})

/**
 * 保存
 */
const save = actionDebounce({
  loadingText: i18n.t('APP.Common.Saving.Text'),
  call: async () => {
    if (pickState.value) return
    let settings = [
      {
        key: BIWD_WATERTREATMENT_CUSTOM_TEMPERATURE,
        value: tempList.value[tempIndex.value[0]].value,
      },
    ]
    if (millVisible.value) {
      settings.push({
        key: BIWD_WATERTREATMENT_CUSTOM_FILLQUANTITY,
        value: millList.value[millIndex.value[0]].value,
      })
    }
    await setHomeApplianceSettings(haId.value, settings)
    await new Promise<void>((resolve) => {
      uni.showToast({
        title: i18n.t('APP.Common.SaveSucess.Text'),
        icon: 'success',
        duration: 2000,
      })
      setTimeout(() => {
        resolve()
        nextTick(() => {
          closeModal()
        })
      }, 2000)
    })
  },
})
</script>

<style lang="less">
@import '../style/favorite.less';
@import '@/styles/common.less';
.custom-program {
  padding: 0 32rpx;
  font-family: PingFang SC;
  font-style: normal;
  .favoriteViewTitle {
    opacity: 1 !important;
  }
  .custom-title {
    margin-top: 24rpx;
    color: var(--dack-color);
    font-size: 64rpx;
    font-weight: 600;
  }
  .custom-img {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 24rpx 0 56rpx;
    .custom-image {
      width: 224rpx;
      height: 224rpx;
      margin: auto;
    }
  }
}
.btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  font-size: 32rpx;
  line-height: 44rpx;
  .save {
    flex-grow: 1;
    font-weight: 600;
    font-size: 32rpx;
    color: var(--primary-color);
    text-align: center;
  }
}
</style>
